package cn.com.w.web.Handler;

import cn.com.w.common.DTO.SysUserDTO;
import cn.com.w.common.Emun.Register;
import cn.com.w.common.Utils.PasswordUtils;
import cn.com.w.common.VO.BaseVO;
import cn.com.w.dao.Service.ISysUserService;
import cn.com.w.secutity.Security.JwtTokenUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author w
 * @Description:
 * @DateTime: 2025 05 07 14:10
 **/
@Component
public class UserHandler {
    @Resource
    ISysUserService userService;
    @Resource
    private JwtTokenUtils tokenUtils;

    /**
     * @author w
     * @Description: 保存一条用户信息 并赋予普通用户权限
     * @DateTime: 2025 05 07 14:49
     * @Params: [username, password, other, type]
     * @Return cn.com.ibibj.login.Common.VO.BaseVO<?>
     */
    public BaseVO<?> saveOne(String username, String password, String other, Register type) {
        try {
            userService.saveOne(SysUserDTO.builder()
                    .username(username)
                    .password(password)
                    .phoneNumber(type.equals(Register.PHONE) ? other : null)
                    .email(type.equals(Register.EMAIL) ? other : null)
                    .wechat(type.equals(Register.WECHAT) ? other : null)
                    .build());
            return BaseVO.builder().code(200).message("注册成功").build();
        } catch (Exception e) {
            return BaseVO.builder().code(200).message("注册失败：" + e.getMessage()).build();
        }
    }

    /**
     * @author w
     * @Description: 根据名称获取token
     * @DateTime: 2025 05 07 14:49
     * @Params: [username]
     * @Return java.lang.String
     */
    public String generalToken(String username) throws Exception {
        SysUserDTO user = userService.loadUserByUsername(username);
        if (user != null) {
            return tokenUtils.generateToken(user);
        }
        return null;
    }

    /**
     * @author w
     * @Description: 密码验证
     * @DateTime: 2025 05 07 14:41
     * @Params: [username, password]
     * @Return boolean
     */
    public boolean checkPassword(String username, String password) throws Exception {
        UserDetails user = userService.loadUserByUsername(username);
        return user.getPassword().equals(PasswordUtils.encryptionPassword(password));
    }
}